package com.example.mqttdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mqttdemo.entity.pojo.SensorData;
import com.example.mqttdemo.entity.pojo.SensorDataPageQuery;
import com.example.mqttdemo.service.SensorDataService;
import com.example.mqttdemo.mapper.SensorDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author wangzihang
 */
@Service
public class SensorDataServiceImpl extends ServiceImpl<SensorDataMapper, SensorData>
        implements SensorDataService {

    @Autowired
    private SensorDataMapper sensorDataMapper;

    @Override
    public IPage<SensorData> pageSensorData(IPage<SensorData> page, SensorDataPageQuery sensorDataPageQuery) {
        QueryWrapper<SensorData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", sensorDataPageQuery.getDeviceId());
        queryWrapper.eq("is_deleted", 0); // 过滤已删除的数据
        queryWrapper.orderByDesc("timestamp"); // 按时间倒序排列（最新的在前）
        if (sensorDataPageQuery.getStartTime() != null) {
            queryWrapper.ge("timestamp", sensorDataPageQuery.getStartTime());
        }
        if (sensorDataPageQuery.getEndTime() != null) {
            queryWrapper.le("timestamp", sensorDataPageQuery.getEndTime());
        }
        IPage<SensorData> pageList = this.page(page, queryWrapper);
        return pageList;
    }

    @Override
    public SensorData getLatestData(String deviceId) {
        SensorData sensorData = sensorDataMapper.selectLatest(deviceId);
        return sensorData;
    }
}




